#!/usr/bin/env python
#coding:utf-8

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.api import users

from django.utils import simplejson as json

import base64
import hashlib
import hmac
import time

class MainPage(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
    	
		if user:
		    self.response.headers['Content-Type'] = 'text/plain'
		    self.response.out.write('Hello ' + user.nickname() )
		else:
			self.redirect(users.create_login_url(self.request.uri))
			
	def post(self):
		self.load_signed_request(self.request.get('signed_request') )
		self.get()
		
		
	def load_signed_request(self,signed_request):
		self.app_secret = "62c35e87a3aede5035293850649ba52e"
		
		sig,payload = signed_request.split(u'.',1)
		sig = self.base64_url_decode(sig)
		data = json.loads(self.base64_url_decode(payload))
		
		self.response.out.write( data )
		
		expected_sig = hmac.new( self.app_secret, msg=payload, digestmod=hashlib.sha256).digest()
		
		if sig == expected_sig and data[u'issued_at'] > (time.time() - 86400):
			self.signed_request = data
			self.user_id = data.get(u'user_id')
			self.access_token = data.get(u'oauth_token')

			self.response.out.write( self.user_id )			

		self.response.out.write( "FIM" )
		
		
	@staticmethod
	def base64_url_decode(data):
		data = data.encode(u'ascii')
		data += '=' * (4 - (len(data) % 4))
		return base64.urlsafe_b64decode(data)

	@staticmethod
	def base64_url_encode(data):
		return base64.urlsafe_b64encode(data).rstrip('=')		
			

application = webapp.WSGIApplication(
                                     [('/', MainPage)],
                                     debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
